package com.msh.starter.common.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CorsFilter implements Filter {

  private String exposedHeaders;

  public CorsFilter(String exposedHeaders) {
    this.exposedHeaders = exposedHeaders;
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {

  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
    httpServletResponse.setHeader("Access-Control-Allow-Methods",
        "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
    httpServletResponse.setHeader("Access-Control-Expose-Headers", exposedHeaders);
    httpServletResponse.setHeader("Access-Control-Request-Headers", "*");
    httpServletResponse.setHeader("Expires", "-1");
    httpServletResponse.setHeader("Cache-Control", "no-cache");
    httpServletResponse.setHeader("pragma", "no-cache");

    chain.doFilter(request, response);

  }

  @Override
  public void destroy() {

  }
}
